import requests
import json
import openpyxl
import xlwt

SEARCH_URL = "http://ad.bytedance.net/audit/hammurabi_facade/api/white_list_v2/249/item/details"
LIVEROOM_ID = 57
SHOP_ID = 55
USER_ID = 56
PRODUCT_ID = 58
COOKIES = {
    "machine_audit_sid": "599e1558-3677-4952-9f9a-3910ad00d0cb",
    "MONITOR_WEB_ID": "dafb5ac7-0c2a-4a67-92e8-7c4eb5dac398",
    "gftoken": "MzI0MjY3OTYyOHwxNjEzNzM1MDE2NzB8fDAGBgYGBgY",
    "audit_adsession_id": "0e494dbc9a5c46f9a864f35810c15b73"
}

x = 1

wk = xlwt.Workbook()
sheet1 = wk.add_sheet("Sheet1", cell_overwrite_ok=True)
sheet1.write(0, 0, "product_id")
sheet1.write(0, 1, "penalize_reason")
sheet1.write(0, 2, "product_name")
sheet1.write(0, 3, "penalize_time")


def save_excel(id, name, time):
    global x
    sheet1.write(x, 0, id)
    sheet1.write(x, 1, "奖惩中心-假货")
    sheet1.write(x, 2, name)
    sheet1.write(x, 3, time)
    x += 1


def is_write(id, type):
    url = SEARCH_URL + "?page_index=1&page_size=10&list_id=" + str(type) + "&"
    if type == LIVEROOM_ID:
        url += "liveroom_id=" + str(id)
    elif type == SHOP_ID:
        url += "shop_id=" + str(id)
    elif type == USER_ID:
        url += "user_id=" + str(id)
    elif type == PRODUCT_ID:
        url += "product_id=" + str(id)

    data = requests.get(url, cookies=COOKIES)
    d = json.loads(data.content)
    if d["data"]["count"] > 0:
        print("already have it")
        return 0
    else:
        return 1


def write(filename, type):
    wb = openpyxl.load_workbook(filename=filename)
    sheet1 = wb["DataPage 1"]

    for i in range(2, sheet1.max_row):
        id = sheet1.cell(row=i, column=1).value
        print("id: ", id, " type: ", type)
        if is_write(id, type) == 1:
            name = sheet1.cell(row=i, column=4).value
            time = sheet1.cell(row=i, column=2).value
            save_excel(id, name, time)


def main():
    filename = "./商品名单-3.19.xlsx"
    write(filename, PRODUCT_ID)

    wk.save("test_商品名单.xls")


if __name__ == '__main__':
    main()
